<template>
  <div class="w-full mx-auto">
    <!-- 管线段标签 -->
    <div class="flex">
      <template v-for="section in pipelineSections" :key="section.name">
        <div
          class="py-2 text-lg font-bold text-center"
          :class="section.bg"
          :style="{
            width: `${getSectionWidth(section)}%`,
            flex: 'none'
          }"
        >
          {{ section.name }}
        </div>
      </template>
    </div>

    <!-- flu标签显示区域 -->
    <!-- <div class="flex mb-2">
      <template v-for="(segment, index) in sortedData" :key="index">
        <div class="text-sm font-bold" :style="{ width: `${getWidthPercentage(segment.bpp)}%` }">
          <span class="flex justify-center">{{ segment.flu }}</span>
        </div>
      </template>
    </div> -->

    <!-- 条形图容器 -->
    <div class="relative h-8 overflow-hidden truncate bg-gray-200 border border-gray-300 rounded-sm" >
      <template v-for="(segment, index) in sortedData" :key="index">
        <div
          class="absolute h-full text-center truncate transition-all duration-200"
          :style="{
            left: `${getLeftPosition(index)}%`,
            width: `${getWidthPercentage(segment.bpp)}%`,
            backgroundColor: getFluColor(segment.flu)
          }"
        ><div class="w-full mt-2 text-xs text-center text-white truncate ">{{ segment.flu }}</div></div>
      </template>
    </div>

    <!-- 底部数值显示 -->
    <div class="relative h-16 mt-3">
      <div class="absolute left-0 right-0 border-t border-gray-300 bottom-10"></div>
      <template v-for="tick in scaleTicks" :key="tick.value">
        <div
          class="absolute flex flex-col items-center"
          :style="{
            left: `${getScalePosition(tick.value)}%`,
            bottom: '38px',
            transform: 'translateX(-50%)'
          }"
        >
          <div
            class="bg-gray-500"
            :class="{'mb-8':!tick.isMajor}"
            :style="{
              width: tick.isMajor ? '1.5px' : '1px',
              height: tick.isMajor ? '14px' : '8px'
            }"
          />
          <span
            v-if="tick.isMajor"
            class="mt-2 text-xs text-gray-700"
          >
            {{ tick.displayValue }}
          </span>
        </div>
      </template>
    </div>
    <div class="-mt-8 text-lg font-bold text-center">km</div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const SCALE_MAX = 85
const TICK_INTERVAL = 2.5
const MAJOR_TICK_INTERVAL = 5
const pipelineSections = [
  { name: '乌百线', start: 0, end: 26.6,bg:'bg-[#e0e0e0]' },
  { name: '百克线', start: 26.6, end: 73.1 ,bg:'bg-[#d0d0d0]'},
  { name: '调油一线', start: 73.1, end: 83.6,bg:'bg-[#e0e0e0]' }
]

const getSectionWidth = (section) => ((section.end - section.start) / SCALE_MAX) * 100
const getScalePosition = (value) => (value / SCALE_MAX) * 100

const props = defineProps({
  batchData: {
    type: Array,
    required: true
  },
  batchDataTy: {
    type: Array,
    required: true
  },
  wb_oil: {
    type: String,
    default: 'WEHY'
  },
  currentTime: {
    type: Number,
    default: 0
  },
  isPlaying: {
    type: Boolean,
    default: true
  },
  timeInterval: {
    type: Number,
    default: 5
  }
})

// 当前数据索引计算
const currentIndex = computed(() => {
  if (!props.batchData?.length) return 0
  return Math.min(Math.floor(props.currentTime / props.timeInterval), props.batchData.length - 1)
})

// 获取当前批次数据
const currentData = computed(() => props.batchData[currentIndex.value])
const currentData_ty = computed(() =>
  props.batchDataTy?.length ? props.batchDataTy[currentIndex.value] || [] : []
)

// 提取并处理管段数据
const extractSegments = (data) => {
  if (!data) return []

  const maxSegments = 10

  return Array.from({ length: maxSegments }, (_, index) => index + 1)
    .map((i) => {
      const value = parseFloat(data[`bpp_${i}`])

      if (!Number.isFinite(value)) return null

      return {
        bpp: value,
        flu: data[`flu_${i}`]
      }
    })
    .filter(Boolean)
}

// Convert boundary points into segment lengths
const sortedData = computed(() => {
  const boundaryPoints = []

  if (props.batchDataTy?.length) {
    boundaryPoints.push({
      bpp: 26.6,
      flu: props.wb_oil
    })
    boundaryPoints.push(...extractSegments(currentData_ty.value))
  }

  boundaryPoints.push(...extractSegments(currentData.value))

  const sortedBoundaries = boundaryPoints
    .filter((item) => Number.isFinite(item.bpp))
    .sort((a, b) => a.bpp - b.bpp)

  let previousEnd = 0

  return sortedBoundaries.reduce((segments, boundary) => {
    const { bpp: end, flu } = boundary

    if (end <= previousEnd) {
      previousEnd = end
      return segments
    }

    segments.push({
      bpp: end - previousEnd,
      flu
    })

    previousEnd = end
    return segments
  }, [])
})

// 计算总长度
const totalLength = computed(() => {
  const sum = sortedData.value.reduce((acc, segment) => acc + segment.bpp, 0)
  return Math.max(sum, SCALE_MAX) || 1
})

// 计算宽度百分比
const getWidthPercentage = (value) => (value / totalLength.value) * 100

// 计算左侧位置
const getLeftPosition = (index) => {
  return sortedData.value
    .slice(0, index)
    .reduce((sum, segment) => sum + getWidthPercentage(segment.bpp), 0)
}

const scaleTicks = computed(() => {
  const totalTicks = Math.round(SCALE_MAX / TICK_INTERVAL)

  return Array.from({ length: totalTicks + 1 }, (_, idx) => {
    const value = Number((idx * TICK_INTERVAL).toFixed(2))
    const ratio = value / MAJOR_TICK_INTERVAL
    const isMajor = Math.abs(ratio - Math.round(ratio)) < 1e-6

    return {
      value,
      isMajor,
      displayValue: isMajor ? Math.round(value).toString() : ''
    }
  })
})

// 颜色管理
const baseColors = [
  '#2ecc71',
  '#3498db',
  '#e74c3c',
  '#9b59b6',
  '#f1c40f',
  '#a3b9d2',
  '#af49d2',
  '#d599d2'
]
const colorMap = ref({})

const getFluColor = (flu) => {
  if (!colorMap.value[flu]) {
    const usedColorCount = Object.keys(colorMap.value).length
    colorMap.value[flu] = baseColors[usedColorCount % baseColors.length]
  }
  return colorMap.value[flu]
}

// 刷新颜色映射
const refreshData = () => {
  colorMap.value = {}
  const allFluLabels = new Set()
  const segmentIndexes = Array.from({ length: 10 }, (_, i) => i + 1)

  // 收集所有flu标签
  props.batchData?.forEach((batch) => {
    segmentIndexes.forEach((i) => {
      const flu = batch[`flu_${i}`]
      if (flu) allFluLabels.add(flu)
    })
  })

  if (props.batchDataTy?.length) {
    allFluLabels.add(props.wb_oil)
    props.batchDataTy.forEach((batch) => {
      segmentIndexes.forEach((i) => {
        const flu = batch[`flu_${i}`]
        if (flu) allFluLabels.add(flu)
      })
    })
  }

  // 分配颜色
  Array.from(allFluLabels).forEach((flu, index) => {
    colorMap.value[flu] = baseColors[index % baseColors.length]
  })
}

// 监听数据变化
watch(
  () => [props.batchData, props.batchDataTy, props.wb_oil],
  refreshData,
  { immediate: true, deep: true }
)

defineExpose({ refreshData })
</script>
